package org.pewpew.model;

import java.util.HashMap;

import org.pewpew.server.GamePhysics;

import com.google.gson.Gson;

public class WorldState {
	private HashMap<String, Player> users = new HashMap<String, Player>();
	private static final int DAMAGE_THRESHOLD = 1;

	public String toJSON() {
		return new Gson ().toJson (this);
	}

	public static WorldState fromJSON(String jsonString) {
		return new Gson ().fromJson(jsonString, WorldState.class);
	}
	
	public Player updatePlayerLocation(String username, double latitude, double longitude, double orientation) {
		if (!users.containsKey(username)) {
			users.put(username, new Player (username, longitude, latitude, orientation));//double set but what the heck
		}
		Player player = users.get (username);
		player.setLatitude (latitude);
		player.setLongitude (longitude);
		player.setOrientation (orientation);
		return player;
	}

	public void shoot(String username) {
		Player attacker = users.get(username);
		for (Player target : users.values()) {
			double damage = GamePhysics.calculateDamageFromShoot(attacker, target);
			if (damage > DAMAGE_THRESHOLD) {
				target.setHealth (target.getHealth () - damage);
			}
			
			if (target.getHealth() < 0) {
				target.setDead(true);
			}
			//TODO all deadmen actions are to be canceled, synchronize
		}
	}

	public void announceDead(final Player victim) {
//do not delete
//		Queue queue = QueueFactory.getDefaultQueue();
//        queue.add(TaskOptions.Builder.withUrl("/notification")
//        		.param("user", victim.getUsername())
//        		.param("status", "alive")
//        		.countdownMillis(DEAD_SUSPEND_TIME));
	}

	public void addObject(Player userInfo) {
		users.put(userInfo.getUsername (), userInfo);
	}
	
	////@JSON
	public HashMap<String, Player> getUsers () {
		return users;
	}

	////@JSON
	public void setUsers (HashMap<String, Player> users) {
		this.users = users;
	}
}
